package grapid.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Freemarker模板类
 * 
 * @author grapid
 * @version 2.0
 * 
 */
public class GFreemarker {

	/**
	 * 默认配置
	 */
	private static Configuration CFG = null;

	/**
	 * 初始化freemarker
	 * 
	 * @param templateFolder
	 *            模板根目录
	 */
	public static void init(String templateFolder) {
		CFG = new Configuration();
		try {
			CFG.setDirectoryForTemplateLoading(new File(templateFolder));
			CFG.setNumberFormat("0.##########");
			CFG.setDefaultEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用freemarker模版取html内容
	 * 
	 * @param templateFilePath
	 *            模板路径
	 * @param data
	 *            传入数据
	 * @return 返回组装的HTML内容
	 */
	public static String getHTML(String templateFilePath, TreeMap<String, Object> data) {
		String html = "";
		Template t = null;
		try {
			t = CFG.getTemplate(templateFilePath);
			t.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			java.io.StringWriter sw = new java.io.StringWriter();
			try {
				t.process(data, sw);
			} catch (TemplateException e) {
				e.printStackTrace();
			}
			html = new String(sw.getBuffer());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return html;
	}

	/**
	 * 使用freemarker模版取html内容
	 * 
	 * @param templateFilePath
	 *            模板路径
	 * @param data
	 *            传入数据
	 * @return 返回组装的HTML内容
	 */
	public static String getHTML(String templateFilePath, Object data) {
		String html = "";
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("data", data);
		Template t = null;
		try {
			t = CFG.getTemplate(templateFilePath);
			t.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			java.io.StringWriter sw = new java.io.StringWriter();
			try {
				t.process(root, sw);
			} catch (TemplateException e) {
				e.printStackTrace();
			}
			html = new String(sw.getBuffer());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return html;
	}
}
